package com.knife.message.api.controller.v1;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.knife.common.utils.Results;
import com.knife.message.app.service.KnifeUserMessageService;
import com.knife.message.domain.entity.KnifeMessage;
import com.knife.message.domain.entity.KnifeUserMessage;
import com.knife.message.domain.service.KnifeEmailSendHelper;
import com.knife.message.infra.mapper.KnifeMessageMapper;
import com.knife.message.infra.mapper.KnifeUserMessageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 用户消息重新发送
 *
 * @author lth
 * @created 2022年09月01日 星期四 9:33
 */
@RestController("KnifeUserMessageController.v1")
@RequestMapping("/v1/{organizationId}/user-message")
public class KnifeUserMessageController {
    @Autowired
    private KnifeUserMessageMapper knifeUserMessageMapper;
    @Autowired
    private KnifeMessageMapper knifeMessageMapper;
    @Autowired
    private KnifeEmailSendHelper knifeEmailSendHelper;
    @Resource
    private KnifeUserMessageService knifeUserMessageService;


    @GetMapping
    public ResponseEntity<Page<KnifeMessage>> selectPage(Page<KnifeMessage> pageRequest, KnifeMessage knifeMessage) {
        return Results.success(knifeUserMessageService.selectPage(pageRequest, knifeMessage));
    }

    @GetMapping("/receiver")
    public ResponseEntity<Page<KnifeUserMessage>> selectReceiverPage(Page<KnifeUserMessage> pageRequest, KnifeUserMessage knifeUserMessage) {
        return Results.success(knifeUserMessageService.selectReceiverPage(pageRequest, knifeUserMessage));
    }


    @GetMapping("/retry")
    public ResponseEntity<String> retrySendMessage(@PathVariable("organizationId") Long organizationId, Long userMessageId, String email) {
        try {
            KnifeUserMessage knifeUserMessage = knifeUserMessageMapper.selectById(userMessageId);
            KnifeMessage knifeMessage = knifeMessageMapper.selectById(knifeUserMessage.getMessageId());
            knifeEmailSendHelper.sendEmail(knifeMessage.getSubject(), knifeMessage.getContent(), email);
            knifeUserMessage.setSendFlag(1);
            knifeUserMessageMapper.updateById(knifeUserMessage);
            return Results.success("发送成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Results.error("发送失败");
        }
    }
}
